<?php

class Application_Model_ChatMapper extends Ahs_Model_Mapper
{
    public function __construct(array $options = null)
    {
        parent::__construct($options);
        $this->DbTableName = 'Application_Model_DbTable_Chats';
    }
    
    
    public function fetchById($id)
     
    {
        $row = $this->getDbTable()->fetchRow(array('chatmessage_id = ?' => $id));
        return $this->_toChat($row);
    }
    
    public function fetchByProjectId($projectId)
    {
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $sql = $db->select()->from('chatmessages')->join('users', 'user_id = chatmessage_user_id')->where('chatmessage_project_id = ?', $projectId)->order('chatmessage_creationdate DESC')->limit(20);
        
        $rows = $db->fetchAll($sql);
        
        //return $this->_toChats($rows);
        
        return $rows;
    }
    
    public function fetchAll()
    {        
       $rows = $this->getDbTable()->fetchAll();
        
       return $this->_toChats($rows);
    }
    
    
    public function addChat($projectId, $userId, $content)
    {
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $count = $db->insert('chatmessages', array('chatmessage_project_id' => $projectId, 'chatmessage_user_id' => $userId, 'chatmessage_content' => $content));
        if($count > 0)
        {
            return true;
        }
        
        return false;
    }
    
    private function _toChat($row = null)
    {
        $chat = new Application_Model_Chat();

        $chat->Id               = $row['chatmessage_id'];
        $chat->ProjectId        = $row['chatmessage_project_id'];
        $chat->UserId           = $row['chatmessage_user_id'];
        $chat->Creationdate     = $row['chatmessage_creationdate'];
        $chat->Content          = $row['chatmessage_content'];
        
        
        return $chat;
    }
    
    private function _toChats($rows = null)
    {
        $chats = array();
        
        foreach($rows as $row)
        {
            $chats[] = $this->_toChat($row);
        }
        
        return $chats;
    }
    
    
    public function save(Application_Model_Chat $chat)
    {
        $data = array(
            'chatmessage_id'                => $chat->Id,
            'chatmessage_project_id'        => $chat->ProjectId,
            'chatmessage_user_id'           => $chat->UserId,
            'chatmessage_creationdate'      => $chat->Creationdate,
            'chatmessage_content'           => $chat->Content,
        );
        
        
        if(null===$chat->Id){
            $this->getDbTable()->insert($data);
        }
        else
        {
           $this->getDbTable()->update($data, array('chatmessage_id = ?' => $chat->Id));
        }
        
    }
    

}

